<template>
  <div class="app-container">
    <el-form :model="form" ref="form" :rules="rules" :inline="true" label-width="100px" v-if="form.appliedStatus<=10">
      <el-row>
        <el-col :span="6">
          <el-form-item label="系" prop="department">
            <el-select class="select-type" v-model="form.department" placeholder="请选择系" @change="departmentChange(form.department)">
              <el-option v-for="item in evaluationDeptOptions" :key="item.deptId" :label="item.deptName"
                         :value="item.deptId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="专业" prop="profession">
            <!--            <label slot="label">专&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业</label>-->
            <el-select class="select-type" v-model="form.profession" clearable placeholder="请选择专业" @change="professionChange(form.profession)">
              <el-option v-for="item in evaluationProfessionOptions" :key="item.deptId" :label="item.deptName"
                         :value="item.deptId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="课程" prop="curriculum">
            <el-autocomplete
              class="inline-input"
              v-model="form.curriculum"
              :fetch-suggestions="querySearch"
              placeholder="请输入课程"
            ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="首次开设时间" prop="firstTime">
            <el-date-picker clearable size="small"
                            v-model="form.firstTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择首次开设时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="总分" prop="totalPoints">
            <el-input
              v-model="form.totalPoints"
              oninput="value=value.replace(/[^\d]/g,'')"
              placeholder="请输入总分"
              clearable
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="自评描述" prop="selfDescription">
            <el-input
              style="width:620px"
              v-model="form.selfDescription"
              type="textarea"
              placeholder="请输入自评"
              :autosize="{ minRows: 3, maxRows: 5}"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :model="form" ref="form" :inline="true" label-width="100px" v-if="form.appliedStatus>10">
      <el-row>
        <el-col :span="6">
          <el-form-item label="系" prop="department">
            <el-select class="select-type" v-model="form.department" clearable disabled placeholder="请选择系">
              <el-option v-for="item in evaluationDeptOptions" :key="item.deptId" :label="item.deptName"
                         :value="item.deptId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="专业" prop="profession">
            <el-select class="select-type" v-model="form.profession" disabled placeholder="请选择专业">
              <el-option v-for="item in evaluationProfessionOptions" :key="item.deptId" :label="item.deptName"
                         :value="item.deptId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="课程" prop="curriculum">
            <el-input
              v-model="form.curriculum"
              placeholder="请输入课程"
              :disabled="true"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="首次开设时间" prop="firstTime">
            <el-date-picker :disabled="true" size="small"
                            v-model="form.firstTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择首次开设时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="总分" prop="totalPoints">
            <el-input
              v-model="form.totalPoints"
              placeholder="请输入总分"
              clearable
              :disabled="true"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="自评" prop="selfDescription">
            <el-input
              style="width:620px"
              v-model="form.selfDescription"
              type="textarea"
              placeholder="请输入自评"
              :disabled="true"
              :autosize="{ minRows: 3, maxRows: 5}"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-show="form.appliedStatus<=10">
        <el-button v-hasRole="['apply']" type="primary" plain size="mini" @click="submitForm">保存</el-button>
      </el-col>
      <el-col :span="1.5" v-show="form.appliedStatus<=10">
        <el-button v-hasRole="['apply']" type="primary" plain size="mini" @click="addIndicator">添加评估项</el-button>
      </el-col>
      <el-col :span="1.5" v-show="form.appliedStatus<=10">
        <el-button v-hasRole="['apply']" type="success" plain size="mini" @click="handleCommit">提交</el-button>
      </el-col>
      <el-col :span="1.5" v-show="form.appliedStatus===20">
        <el-button v-hasRole="['audit']" type="warning" plain size="mini" @click="checkCommit">审核</el-button>
      </el-col>
      <el-col :span="1.5" v-show="form.appliedStatus===20">
        <el-popover placement="right-start" width="500" trigger="click" v-model="visible">
          <el-form ref="rejectForm" :model="rejectForm" label-width="80px">
            <el-form-item label="驳回原因" prop="remark">
              <el-input v-model="rejectForm.modifiedCause" :autosize="{ minRows: 4, maxRows: 6}" type="textarea" placeholder="请输入原因"></el-input>
            </el-form-item>
          </el-form>
          <div style="text-align: right; margin: 0">
            <el-button type="primary" @click="submitRejectForm">确 定</el-button>
            <el-button @click="cancelRejectForm">取 消</el-button>
          </div>
          <el-button v-hasRole="['audit']" slot="reference" type="danger" plain size="mini">驳回</el-button>
        </el-popover>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="exportExcel()"
        >导出
        </el-button>
      </el-col>
    </el-row>

    <el-table id="out-table" v-loading="loading"
              :data="applicationItemList"
              border @selection-change="handleSelectionChange"
              @cell-dblclick="handleFocus"
              :span-method="objectSpanMethod"
              :row-class-name="tableRowClassNames"
              ref="report-table"
    >
      <el-table-column :label="form.curriculum">
        <el-table-column :label='"系："+this.departmentName+"，专业："+this.professionName+"，首次开设时间："+this.form.firstTime'>
          <el-table-column label="一级指标" align="center" width="150" prop="firstItem.evaluationIndicatorDescription">
            <template slot-scope="scope">
              <span>{{ scope.row.firstItem.evaluationIndicatorDescription }}</span>
              <el-input size="small" oninput="value=value.replace(/[^\d]/g,'')" v-model="scope.row.firstItem.evaluationWeight"
                        v-show="scope.row.firstWeightShow"
                        maxlength="3"
                        v-focus
                        @blur="handleMissFocus(scope.$index,scope.row.firstItem,'firstEvaluationWeight')"/>
              <span v-show="!scope.row.firstWeightShow">{{ '(' + scope.row.firstItem.evaluationWeight + '分)' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="二级指标" align="center" width="200" prop="secondItem.evaluationIndicatorDescription">
            <template slot-scope="scope">
              <span>{{ scope.row.secondItem.evaluationIndicatorDescription }}</span>
              <el-input size="small" oninput="value=value.replace(/[^\d]/g,'')" v-model="scope.row.secondItem.evaluationWeight"
                        v-show="scope.row.secondWeightShow"
                        maxlength="3"
                        v-focus
                        @blur="handleMissFocus(scope.$index,scope.row.secondItem,'secondEvaluationWeight')"/>
              <span v-show="!scope.row.secondWeightShow" v-html="calculationtwo(scope.row)"></span>
            </template>
          </el-table-column>
          <el-table-column label="主要观测要素" align="center" width="300" prop="evaluationIndicatorDescription">
            <template slot-scope="scope">
              <span v-html="calculationone(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="考核/协助部门" align="center" width="150" prop="evaluationIndicatorDescription">
            <template slot-scope="scope">
              <span>{{ scope.row.assistDeptName ? scope.row.assistDeptName : "" + '/' + scope.row.evaluationDeptName ? scope.row.evaluationDeptName : "" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="观测要素量化考核标准" align="center" width="200" prop="observation">
            <template slot-scope="scope">
             <span v-html="cutout(scope.row.observation)">
          </span>
            </template>
          </el-table-column>
          <el-table-column label="指标权重" align="center" prop="evaluationWeight">
            <template slot-scope="scope">
              <el-input size="small" oninput="value=value.replace(/[^\d]/g,'')" v-model="scope.row.evaluationWeight"
                        v-show="scope.row.weightShow"
                        maxlength="3"
                        v-focus
                        @blur="handleMissFocus(scope.$index,scope.row,'evaluationWeight')"/>
              <span v-show="!scope.row.weightShow">{{ scope.row.evaluationWeight + '%' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="自评级别" align="center" prop="selfLevel">
            <template slot-scope="scope">
              <el-select v-model="scope.row.selfLevel" v-show="scope.row.levelShow" filterable clearable placeholder="请选择级别"
                         @visible-change="handleSelectMissFocus($event,scope.$index,scope.row,'selfLevel')">
                <el-option
                  v-for="dict in scope.row.evaluationItemRangeList"
                  :key="dict.evaluationRangeId"
                  :label="dict.levelValue"
                  :value="dict.levelValue"
                />
              </el-select>
              <span v-show="!scope.row.levelShow">{{ scope.row.selfLevel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="自评分" align="center" prop="selfScore"/>
          <el-table-column label="作证材料" align="center" prop="fileName">
            <template slot-scope="scope">
              <el-link :href="`${baseUrl}${scope.row.filePath}`" :underline="false" target="_blank">
                <span class="el-icon-document" v-if="scope.row.fileName"> {{ scope.row.fileName }} </span>
              </el-link>
              <div class="ele-upload-list__item-content-action" v-if="scope.row.fileName&&form.appliedStatus<=10">
                <el-link :underline="false" @click="handleDelete(scope.row)" type="danger">删除</el-link>
              </div>
              <el-upload
                v-if="!scope.row.fileName&&form.appliedStatus<=10"
                multiple
                :action="uploadFileUrl"
                :before-upload="handleBeforeUpload"
                :file-list="fileList"
                :limit=1
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                :on-success="handleUploadSuccess"
                :show-file-list="false"
                :headers="headers"
                class="upload-file-uploader"
                ref="upload"
              >
                <el-link :underline="false" @click="changeRow(scope.row)" type="primary">上传</el-link>
                <div class="el-upload__tip" slot="tip" v-if="showTip">
                  请上传
                  <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
                  <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
                  的文件
                </div>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="改进措施" align="center" width="150" prop="rectify">
            <template slot-scope="scope">
              <el-input type="textarea" size="small" v-model="scope.row.rectify"
                        v-show="scope.row.rectifyShow"
                        @blur="handleMissFocus(scope.$index,scope.row,'rectify')"/>
              <span v-show="!scope.row.rectifyShow">{{ scope.row.rectify }}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>
    <el-dialog :title="title" :visible.sync="open" width="60%" height="500" append-to-body>
      <el-form :model="indicatorForm" ref="indicatorForm" label-width="80px">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText">
        </el-input>
        <el-form-item label="评估指标" class="tree">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-tree
            class="filter-tree"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="false"
            :filter-node-method="filterNode"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          >
            <template slot-scope="{ node, data }">
              <div style="font-size:12px;">
                <span class="overflow-x: auto"> {{ node.label }}</span>
              </div>
            </template>
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTable">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getApplication,
  addApplication,
  updateApplication,
  getIndicator,
  addIndicator,
  getItemRange,
  updateApplicationItem,
  rejectApplication,
  saveItemFile,
  checkItemRange,
  listDictCurriculums,
  auditApplication,
  submitApplication
} from "@/api/business/evaluationApplication";
import {listEvaluation} from "@/api/business/evaluationIndicator";

import math from "@/api/tool/moth";

import FileSaver from "file-saver"
import * as XLSX from 'xlsx/xlsx.mjs';
import XLSXS from "xlsx-style"
import userAvatar from "@/views/system/user/profile/userAvatar";
import {getToken} from "@/utils/auth";
import {listDept} from "@/api/system/dept";

export default {
  name: "Application",
  props: {
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "zip", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  components: {userAvatar},
  directives: {
    focus: {
      // 指令的定义
      update: function (el) {
        el.querySelector('input').focus();
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.menu.filter(val);
    },
  },
  data() {
    return {
      number: 0,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      printLoading: true,
      // 遮罩层
      loading: true,
      visible: false,
      fileList: [],
      currentRow: null,
      departmentName: "",
      professionName: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      menuExpand: false,
      menuNodeAll: false,
      evaluationDeptOptions: [],
      evaluationProfessionOptions: [],
      evaluationCurriculums: [],
      filterText: '',
      // 菜单列表
      menuOptions: [],
      // 总条数
      total: 0,
      // 评估申请表格数据
      applicationList: [],
      applicationItemList: [],
      evaluationIndicatorList: [],
      isExpandAll: false,
      refreshTable: true,
      multipleSelection: [],
      // 选中数组
      indicatorIds: [],
      indicatorSelection: [],
      applicationId: null,
      search: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        evaluationStandardId: null,
        department: null,
        profession: null,
        curriculum: null,
        firstTime: null,
        person: null,
        description: null,
        appliedStatus: null,
        appliedBy: null,
        auditedBy: null,
        createdAt: null,
        modifiedAt: null,
        submittedAt: null,
        auditedAt: null,
        canceledAt: null
      },
      // 表单参数
      form: {
        evaluationApplicationId: null,
        evaluationStandardId: null,
        department: '',
        deptId: '',
        label: '', professionLabel: '',
        profession: '',
        curriculum: '',
        firstTime: '',
        person: null,
        description: null,
        appliedStatus: 0,
        appliedBy: null,
        auditedBy: null,
        createdAt: null,
        modifiedAt: null,
        submittedAt: null,
        auditedAt: null,
        canceledAt: null,
        totalPoints: 100
      },
      rejectForm: {},
      indicatorForm: {evaluationApplicationId: null, modifiedCause: null},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      // 表单校验
      rules: {
        department: [
          {required: true, message: "系不能为空", trigger: "change"}
        ],
        profession: [
          {required: true, message: "专业不能为空", trigger: "change "}
        ],
        curriculum: [
          {required: true, message: "课程不能为空", trigger: "blur"}
        ],
        totalPoints: [
          {required: true, message: "总分不能为空", trigger: "blur"}
        ]
      },
      firstItemColumn: [],
      secondItemColumn: []
    };
  },
  created() {
    if (this.$route.params && this.$route.params.applicationId) {
      this.applicationId = this.$route.params.applicationId;
    }
    this.getDepartmentList();
    this.getItemRange(this.applicationId);
    this.handleUpdate(this.applicationId);
    this.getCurriculumList();
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {

    exportExcel(excelName) {
      // 为el-table添加一个id：out-table
      // 当el-table使用了fixed时会导出两次数据，所以要先进行判断
      let fix = document.querySelector('.el-table__fixed');
      let wb;
      if (fix) {
        // 如果有fixed，先移除，然后再添加上
        wb = XLSX.utils.table_to_book(document.querySelector("#out-table").removeChild(fix))
        document.querySelector("#out-table").appendChild(fix)
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#out-table"))
      }
      // 设置列宽 字号等
      this.setExlStyle(wb['Sheets']['Sheet1']);
      let wbout = XLSXS.write(wb, {
        type: "buffer"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: "application/octet-stream"
          }),
          // 导出的文件名称
          "Data.xlsx"
        )
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    setExlStyle(data) {
      //单元格外侧框线
      const borderAll = {
        top: {
          style: 'thin',
        },
        bottom: {
          style: 'thin'
        },
        left: {
          style: 'thin'
        },
        right: {
          style: 'thin'
        }
      };
      data['!cols'] = [];
      for (let key in data) {
        if (data[key] instanceof Object) {
          // 内容不为空
          if (data[key].v !== '') {
            // 首行
            if (key[1].toString() === "1") {
              data[key].s = {
                // 边框
                // border: borderAll,
                // 居中
                alignment: {
                  horizontal: 'center', vertical: 'center'
                },
                font: {name: '微软雅黑', sz: 18, bold: true},
                // 背景色
                // fill: {bgColor: {indexed: 64}, fgColor: {rgb: "FFFF00"}}
              }
            } else if (key[1].toString() === "2") {
              data[key].s = {
                // 边框
                // border: borderAll,
                // 居中
                alignment: {
                  horizontal: 'center', vertical: 'center'
                },
                font: {name: '微软雅黑', sz: 16, bold: true}
              }
            } else if (key[1].toString() === "3") {
              data[key].s = {
                // 边框
                // border: borderAll,
                // 居中
                alignment: {
                  horizontal: 'center', vertical: 'center'
                },
                font: {name: '微软雅黑', sz: 14, bold: true}
              }
            } else {
              data[key].s = {
                // border: borderAll,
                // 自动换行
                alignment: {
                  horizontal: 'center', vertical: 'center', wrapText: 1
                },
                font: {name: '微软雅黑', sz: 11},
                numFmt: 0
              }
            }
            // 定义列宽
            if (key[1].toString() === "3") {
              let len = String(data[key].v).length
              let w = 0
              switch (String(data[key].v).length) {
                case 3:
                  w = 80;
                  break;
                case 4:
                  w = 100;
                  break;
                case 6:
                  w = 300;
                  break;
                default:
                  w = 200;
              }
              data['!cols'].push({wpx: w});
            }
          }
        }
      }
      return data;
    },
    /** 查询评估申请明细列表 */
    getItemRange(applicationId) {
      this.loading = true;
      let data = {applicationId: applicationId}
      getItemRange(data).then(response => {
        this.applicationItemList = response.data;
        //进行行合并处理
        this.getListDataForRowAndColumn(this.applicationItemList)
        console.log("评估明细项", this.applicationItemList)
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        evaluationApplicationId: null,
        evaluationStandardId: null,
        department: null,
        profession: null,
        curriculum: null,
        firstTime: null,
        person: null,
        description: null,
        appliedStatus: 0,
        appliedBy: null,
        auditedBy: null,
        createdAt: null,
        modifiedAt: null,
        submittedAt: null,
        auditedAt: null,
        canceledAt: null,
        totalPoints: 100
      };
      this.resetForm("form");
    },
    // 驳回表单重置
    resetRejectForm() {
      this.rejectForm = {
        modifiedCause: null
      };
      this.resetForm("rejectForm");
    },
    indicatorReset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.indicatorForm = {
          menuCheckStrictly: true
        };
      this.resetForm("indicatorForm");
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.evaluationApplicationId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.multipleSelection = selection
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加评估申请";
    },

    /** 申请信息查询按钮操作 */
    handleUpdate(evaluationApplicationId) {
      getApplication(evaluationApplicationId).then(response => {
        console.log("申请单查询结果1", response.data)
        if (response.data) {
          this.form = response.data;
          var obj = this.evaluationDeptOptions.find((item) => item.deptId == response.data.department);
          if (obj) {
            this.departmentName = obj.deptName;
          } else {
            this.departmentName = "";
          }
          if (this.form.department) {
            this.getProfessionList(this.form.department);
          }
          this.rejectForm.evaluationApplicationId = this.form.evaluationApplicationId
          if (this.form.firstTime == null)
            this.form.firstTime = "";
        }
      });
    },
    /** 查询自定义系字典列表 */
    getCurriculumList() {
      listDictCurriculums().then(response => {
        if (response.data) {
          this.evaluationCurriculums = response.data.map((item) => {
            return {
              label: item.curriculum,
              value: item.curriculum
            };
          });
        }
        console.log("查询-课程自定义", this.evaluationCurriculums)
      });
    },
    getDepartmentList() {
      const queryDept = {parentId: 200, status: 0}
      //listDictSelect
      listDept(queryDept).then(response => {
        console.log("查询-系", response.data)
        this.evaluationDeptOptions = response.data;
      });
    },
    departmentChange(parentId) {
      var obj = this.evaluationDeptOptions.find((item) => item.deptId == this.form.department);
      if (obj) {
        this.departmentName = obj.deptName;
      } else {
        this.departmentName = "";
      }
      this.getProfessionList(parentId);
    },
    getProfessionList(parentId) {
      const queryDept = {parentId: parentId, status: 0}
      //listDictSelect
      listDept(queryDept).then(response => {
        console.log("查询-专业", response.data)
        this.evaluationProfessionOptions = response.data;
        var obj1 = this.evaluationProfessionOptions.find((item) => item.deptId == this.form.profession);
        if (obj1) {
          this.form.profession = obj1.deptId;
          this.professionName = obj1.deptName;
          console.log(" 初始this.professionName" + this.professionName)
        } else {
          this.professionName = "";
          this.form.profession = "";
        }
      });
    },
    professionChange(profession) {
      var obj1 = this.evaluationProfessionOptions.find((item) => item.deptId == profession);
      if (obj1) {
        this.professionName = obj1.deptName;
        console.log(" changethis.professionName" + this.professionName)
      } else {
        this.professionName = "";
      }
    },
    /** 提交按钮操作 */
    handleCommit() {
      this.$modal.confirm('是否确认提交评估申请？').then(function () {
        return;
      }).then(() => {
        if (this.form.evaluationApplicationId == '' || this.form.evaluationApplicationId == null) {
          this.$modal.msgError("请先保存申请");
          return;
        }
        this.loading = true;
        let data = {applicationId: this.form.evaluationApplicationId}
        checkItemRange(data).then(response => {
          console.log("校验返回结果", response.data)
          if (response.data.code == "1") {
            this.loading = false;
            this.$modal.msgError(response.data.msg);
            return;
          } else if (response.data.code == "2") {
            this.loading = false;
            this.$modal.msgError(response.data.msg);
            return;
          } else if (response.data.code == "3") {
            this.loading = false;
            this.$modal.msgError(response.data.msg);
            return;
          } else {
            //校验是否全部评分
            this.applicationItemList.forEach((item) => {
              if (item.selfLevel == "" || item.selfLevel == null) {
                item.isRed = true;
              } else {
                item.isRed = false;
              }
            });
            //筛选数量
            const selfLevelList = this.applicationItemList.filter(item => item.isRed)
            if (selfLevelList.length > 0) {
              this.$modal.msgError("有未自评的项目，请核实！");
              this.loading = false;
              return;
            }

            const updateForm = {evaluationApplicationId: this.form.evaluationApplicationId, appliedStatus: 20}
            submitApplication(updateForm).then(response => {
              this.$modal.msgSuccess("提交成功");
              this.loading = false;
              this.closeRefreshPage();
            });
          }
        });
      }).catch(() => {
      });

    },
    /** 审核按钮操作 */
    checkCommit() {
      const updateForm = {evaluationApplicationId: this.form.evaluationApplicationId}
      auditApplication(updateForm).then(response => {
        this.$modal.msgSuccess("审核成功");
        this.handleUpdate(this.form.evaluationApplicationId);
        this.closeRefreshPage();
      });
    },
    /** 申请保存提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.evaluationApplicationId != null) {
            updateApplication(this.form).then(response => {
              this.getItemRange(this.form.evaluationApplicationId);
              this.handleUpdate(this.form.evaluationApplicationId);
              this.$modal.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            addApplication(this.form).then(response => {
              console.log("新增返回id", response.data.evaluationApplicationId)
              this.getItemRange(response.data.evaluationApplicationId);
              this.handleUpdate(response.data.evaluationApplicationId);
              this.$modal.msgSuccess("新增成功");
              this.open = false;
            });
          }
        }
      });
    },
    /** 申请驳回按钮 */
    submitRejectForm() {
      rejectApplication(this.rejectForm).then(response => {
        this.$modal.msgSuccess("驳回成功");
        this.visible = false;
        this.resetRejectForm();
        this.getItemRange(this.form.evaluationApplicationId);
        this.handleUpdate(this.form.evaluationApplicationId);
        this.closeRefreshPage();
      });
    },
    /** 申请驳回取消按钮 */
    cancelRejectForm() {
      this.visible = false;
      this.resetRejectForm();
    },
    getEvaluationIndicatorList() {
      this.loading = true;
      let queryParams = {canceledAt: "0"}
      listEvaluation(queryParams).then(response => {
        this.evaluationIndicatorList = this.handleTree(response.data, "evaluationIndicatorId");
        this.loading = false;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 多选框选中数据
    indicatorSelectionChange(selection) {
      this.indicatorIds = selection.map(item => item.evaluationIndicatorId)
      this.indicatorSelection = selection
    },
    /** 添加评估直指标按钮操作 */
    addIndicator() {
      if (this.form.evaluationApplicationId == '' || this.form.evaluationApplicationId == null) {
        this.$modal.msgError("请先保存申请");
        return;
      }
      this.indicatorReset();
      this.open = true;
      this.title = "添加评估项";
      getIndicator(this.form.evaluationApplicationId).then(response => {
        this.menuOptions = response.indicator;
        let checkedKeys = response.checkedKeys;
        console.log("返回选中", checkedKeys)
        checkedKeys.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false);
          })
        })
      });
    },
    submitTable() {
      //过去选中的指标项
      const indicatorIds = this.getMenuAllCheckedKeys();
      console.log("获取添加指标项", indicatorIds)
      let data = {applicationId: this.form.evaluationApplicationId, indicatorIds: indicatorIds}
      addIndicator(data).then(response => {
        this.$modal.msgSuccess("添加成功");
        this.open = false;
        this.getItemRange(this.form.evaluationApplicationId);
        this.handleUpdate(this.form.evaluationApplicationId);
      });
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },

    /** 删除作证材料操作 */
    handleDelete(row) {
      const updateForm = {evaluationItemId: row.evaluationItemId, fileName: '', filePath: ''}
      saveItemFile(updateForm).then(response => {
        this.$modal.msgSuccess("删除成功");
        row.fileName = "";
        row.filePath = "";
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('evaluation/application/export', {
        ...this.queryParams
      }, `application_${new Date().getTime()}.xlsx`)
    },
    /*******处理指标表格树形多级单选/全选 开始 *******/
    rowSelect(selection, row) {
      if (selection.some(el => {
        return row.evaluationIndicatorId === el.evaluationIndicatorId
      })) {
        if (row.children) {
          row.children.map(j => {
            this.toggleSelection(j, true)
            //判断是否存在三级子节点
            if (j.children) {
              j.children.map((itemChildren) => { //遍历所有子节点
                this.toggleSelection(itemChildren, true) //切换该子节点选中状态
              });
            }
          })
        }
      } else {
        if (row.children) {
          row.children.map(j => {
            this.toggleSelection(j, false)
            //判断是否存在三级子节点
            if (j.children) {
              j.children.map((itemChildren) => { //遍历所有子节点
                this.toggleSelection(itemChildren, false) //切换该子节点选中状态
              });
            }
          })
        }
      }
    },
    selectAll(selection) {

      // tabledata第一层只要有在selection里面就是全选
      const isSelect = selection.some(el => {
        const tableDataIds = this.evaluationIndicatorList.map(j => j.evaluationIndicatorId)
        return tableDataIds.includes(el.evaluationIndicatorId)
      })
      // tableDate第一层只要有不在selection里面就是全不选
      const isCancel = !this.evaluationIndicatorList.every(el => {
        const selectIds = selection.map(j => j.evaluationIndicatorId)
        return selectIds.includes(el.evaluationIndicatorId)
      })
      if (isSelect) {
        selection.forEach(item => {
          if (item.children) {
            item.children.map((item1) => { //遍历所有子节点
              this.toggleSelection(item1, true); //切换该子节点选中状态

              if (item1.children) {
                item1.children.map((itemChildren) => { //遍历所有子节点
                  this.toggleSelection(itemChildren, true); //切换该子节点选中状态
                });
              }
            });
          }
        });
      }
      if (isCancel) {
        //这里取消全选用selection集合，二级不能取消全选，但是用tableData集合就没问题，没想明白
        this.evaluationIndicatorList.forEach(item => {
          if (item.children) {
            item.children.map((item1) => { //遍历所有子节点
              this.toggleSelection(item1, false); //切换该子节点选中状态
              if (item1.children) {
                item1.children.map((itemChildren) => { //遍历所有子节点
                  this.toggleSelection(itemChildren, false); //切换该子节点选中状态
                });
              }
            });
          }
        });
      }
    },
    toggleSelection(row, selected) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.table && this.$refs.table.toggleRowSelection(row, selected)
        })
      }
    },
    /*******处理指标表格树形多级单选/全选 结束 *******/
    /** 打开行内编辑 */
    handleFocus(index, column) {
      console.log("点击列", column)
      if (this.form.appliedStatus <= 10) {
        switch (column.property) {
          case "firstItem.evaluationIndicatorDescription":
            index.firstWeightShow = true;
            break;
          case "secondItem.evaluationIndicatorDescription":
            index.secondWeightShow = true;
            break;
          case "evaluationWeight":
            index.weightShow = true;
            break;
          case "selfLevel":
            index.levelShow = true;
            break;
          case "rectify":
            index.rectifyShow = true;
            break;
        }
      }
    },
    handleMissFocus(index, row, columnName) {

      const updateForm = {
        evaluationItemId: row.evaluationItemId,
        evaluationWeight: null
      }
      if (columnName === 'firstEvaluationWeight') {
        updateForm.evaluationWeight = row.evaluationWeight
        if (updateForm.evaluationWeight == '' || updateForm.evaluationWeight == null) {
          this.$modal.msgError("分数不能为空");
          return;
        }
        //一级二级重新计算指标评分
        updateApplicationItem(updateForm).then(response => {
          this.applicationItemList[index].weightShow = false;
          this.applicationItemList[index].levelShow = false;
          this.applicationItemList[index].firstWeightShow = false;
          this.applicationItemList[index].secondWeightShow = false;
          //该父级下所有子集重新计算评分
          this.applicationItemList.forEach((item, index) => {
            if (item.firstItem.evaluationItemId == row.evaluationItemId) {
              //先更新子集的父级的分数，不然计算出来的分值不正确
              item.firstItem.evaluationWeight = row.evaluationWeight
              const scoreForm = {
                evaluationItemId: item.evaluationItemId,
                selfScore: null
              }
              //重新计算
              scoreForm.selfScore = item.selfScore;
              let selfScore = item.selfScore;
              const range = item.evaluationItemRangeList.filter(v => v.levelValue == item.selfLevel)
              if (range.length > 0) {
                selfScore = (math.multiply(item.firstItem.evaluationWeight * item.secondItem.evaluationWeight * item.evaluationWeight * range[0].evaluationProportion,0.0001)).toFixed(2);
                if (selfScore == 'NaN') {
                  return true;
                }
                scoreForm.selfScore = selfScore;
              }
              if (scoreForm.selfScore) {
                updateApplicationItem(scoreForm).then(response => {
                  //重新赋值
                  item.selfScore = scoreForm.selfScore;
                });
              }
            }
          });
        });
      } else if (columnName === 'secondEvaluationWeight') {
        updateForm.evaluationWeight = row.evaluationWeight
        if (updateForm.evaluationWeight == '' || updateForm.evaluationWeight == null) {
          this.$modal.msgError("占比不能为空");
          return;
        }
        //一级二级重新计算指标评分
        console.log("编辑入参", updateForm)
        updateApplicationItem(updateForm).then(response => {
          this.applicationItemList[index].weightShow = false;
          this.applicationItemList[index].levelShow = false;
          this.applicationItemList[index].firstWeightShow = false;
          this.applicationItemList[index].secondWeightShow = false;
          //该父级下所有子集重新计算评分
          this.applicationItemList.forEach((item, index) => {
            if (item.secondItem.evaluationItemId == row.evaluationItemId) {
              //先更新子集的父级的占比，不然计算出来的分值不正确
              item.secondItem.evaluationWeight = row.evaluationWeight
              const scoreForm = {
                evaluationItemId: item.evaluationItemId,
                selfScore: null
              }
              //重新计算
              scoreForm.selfScore = item.selfScore;
              const range = item.evaluationItemRangeList.filter(v => v.levelValue == item.selfLevel)
              if (range.length > 0) {
                let selfScore = (math.multiply(item.firstItem.evaluationWeight * item.secondItem.evaluationWeight * item.evaluationWeight * range[0].evaluationProportion,0.000001)).toFixed(2);
                if (selfScore == 'NaN') {
                  return true;
                }
                scoreForm.selfScore = selfScore;
              }
              if (scoreForm.selfScore) {
                updateApplicationItem(scoreForm).then(response => {
                  //重新赋值
                  item.selfScore = scoreForm.selfScore;
                });
              }
            }
          });
        });
      } else if (columnName === 'evaluationWeight') {
        updateForm.evaluationWeight = row.evaluationWeight
        if (updateForm.evaluationWeight == '' || updateForm.evaluationWeight == null) {
          this.$modal.msgError("权重不能为空");
          return;
        }
        updateApplicationItem(updateForm).then(response => {
          this.applicationItemList[index].weightShow = false;
          this.applicationItemList[index].levelShow = false;
          this.applicationItemList[index].firstWeightShow = false;
          this.applicationItemList[index].secondWeightShow = false;
          //重新计算
          const scoreForm = {
            evaluationItemId: row.evaluationItemId,
            selfScore: null
          }
          scoreForm.selfScore = row.selfScore;
          const range = row.evaluationItemRangeList.filter(item => item.levelValue == row.selfLevel)
          if (range.length > 0) {
            let selfScore = (math.multiply(row.firstItem.evaluationWeight * row.secondItem.evaluationWeight * row.evaluationWeight * range[0].evaluationProportion,0.000001)).toFixed(2);
            if (selfScore == 'NaN') {
              return;
            }
            scoreForm.selfScore = selfScore;
          }
          if (scoreForm.selfScore) {
            updateApplicationItem(scoreForm).then(response => {
              row.selfScore = scoreForm.selfScore;
            });
          }
        });
      } else {
        //重新计算
        const rectifyForm = {
          evaluationItemId: row.evaluationItemId,
          rectify: row.rectify
        }
        updateApplicationItem(rectifyForm).then(response => {
          this.applicationItemList[index].weightShow = false;
          this.applicationItemList[index].levelShow = false;
          this.applicationItemList[index].firstWeightShow = false;
          this.applicationItemList[index].secondWeightShow = false;
          this.applicationItemList[index].rectifyShow = false;
        });
      }
    },
    handleSelectMissFocus(callback, index, row, columnName) {
      if (!callback) {
        if (columnName === 'selfLevel') {
          const updateForm = {
            evaluationItemId: row.evaluationItemId,
            selfLeve: null
          }
          updateForm.selfLevel = row.selfLevel
          if (updateForm.selfLevel == '' || updateForm.selfLevel == null) {
            this.$modal.msgError("自评级别不能为空");
            return;
          }
          console.log("编辑入参", updateForm)
          updateApplicationItem(updateForm).then(response => {
            this.applicationItemList[index].weightShow = false;
            this.applicationItemList[index].levelShow = false;
            this.applicationItemList[index].firstWeightShow = false;
            this.applicationItemList[index].secondWeightShow = false;
            //重新计算
            const scoreForm = {
              evaluationItemId: row.evaluationItemId,
              selfScore: null
            }
            scoreForm.selfScore = row.selfScore;
            const range = row.evaluationItemRangeList.filter(item => item.levelValue == row.selfLevel)
            if (range.length > 0) {
              let selfScore = (math.multiply(row.firstItem.evaluationWeight * row.secondItem.evaluationWeight * row.evaluationWeight * range[0].evaluationProportion,0.000001)).toFixed(2);
              if (selfScore == 'NaN') {
                return;
              }
              scoreForm.selfScore = selfScore;
            }
            if (scoreForm.selfScore) {
              updateApplicationItem(scoreForm).then(response => {
                row.selfScore = scoreForm.selfScore;
              });
            }
          });
        }
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false;
      }
    },
    /**  评估明细项表格一级二级合并行操作开始 **/
    //判断需要合并行，进行数组组装
    getListDataForRowAndColumn(data) {
      let self = this;
      self.firstItemColumn = [];
      self.secondItemColumn = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          // 如果是第一条记录（即索引是0的时候），向数组中加入１
          self.firstItemColumn.push(1);
          self.pos = 0;
          self.secondItemColumn.push(1);
          self.posT = 0;
        } else {
          if (data[i].firstItem.evaluationItemId === data[i - 1].firstItem.evaluationItemId) {
            // 如果storeName相等就累加，并且push 0
            self.firstItemColumn[self.pos] += 1
            self.firstItemColumn.push(0)
            if (data[i].secondItem.evaluationItemId === data[i - 1].secondItem.evaluationItemId) {
              // 如果roomName相等就累加，并且push 0
              self.secondItemColumn[self.posT] += 1
              self.secondItemColumn.push(0)
            } else {
              self.secondItemColumn.push(1)
              self.posT = i
            }
          } else {
            // 不相等push 1
            self.firstItemColumn.push(1)
            self.pos = i;
            self.secondItemColumn.push(1)
            self.posT = i
          }
        }
      }
    },
    //行合并
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      let self = this
      if (columnIndex === 0) {
        if (self.firstItemColumn[rowIndex]) {
          let rowNum = self.firstItemColumn[rowIndex];
          return {
            rowspan: rowNum,
            colspan: rowNum > 0 ? 1 : 0
          }
        }
        return {
          rowspan: 0,
          colspan: 0
        }
      }
      if (columnIndex === 1) {
        if (self.secondItemColumn[rowIndex]) {
          let roomNum = self.secondItemColumn[rowIndex];
          return {
            rowspan: roomNum,
            colspan: roomNum > 0 ? 1 : 0
          }
        }
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    },
    /**  评估明细项表格一级二级合并行操作结束 **/
    cutout(cellValue) {
      return cellValue.replaceAll('|', '<br/>')
    },
    calculationone(row) {
      return row.evaluationIndicatorDescription + '(' + math.multiply(row.firstItem.evaluationWeight * row.secondItem.evaluationWeight * row.evaluationWeight,0.0001)+ '分)'
    },
    calculationtwo(row) {
      return '(' + row.secondItem.evaluationWeight + '%)' + '(' +math.multiply(row.firstItem.evaluationWeight * row.secondItem.evaluationWeight,0.01) + '分)'
    },
    /**行字体颜色 */
    tableRowClassNames(val) {
      if (val.row.isRed) {
        return 'red-row';
      } else {
        return '';
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      console.log("文件上传返回结果", res)
      this.$modal.closeLoading();
      const updateForm = {evaluationItemId: this.currentRow.evaluationItemId, fileName: res.newFileName, filePath: res.fileName}
      saveItemFile(updateForm).then(response => {
        this.$modal.msgSuccess("上传成功");
        this.getItemRange(this.form.evaluationApplicationId);
      });
    },
    /** 材料上传点击 */
    changeRow(row) {
      this.currentRow = row;
      console.log("当前点击行", this.currentRow)
    },
    querySearch(queryString, cb) {
      this.getCurriculumList();
      var restaurants = this.evaluationCurriculums;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    /** 关闭当前页并刷新首页 */
    closeRefreshPage() {
      const obj = {path: "/index", query: {refresh: true}};
      this.$tab.closeOpenPage(obj);
    },
  },
};

</script>
<style lang="scss">
.tree {
  .el-tree-node {
    white-space: normal;

    .el-tree-node__content {
      height: 100%;
      align-items: start;
    }
  }
}

table {
  font-family: Arial, sans-serif;
  font-size: 14px;
  background-color: #f0f2f5;
  border-collapse: collapse;
  color: #454545;
  table-layout: auto;
  width: 100%;
  text-align: center;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: #dadcde;

  thead {
    border-top-width: 1px;
    border-top-style: solid;
    border-top-color: #dadcde;
    line-height: 40px;
    font-weight: bold;
    color: #454c70;
  }

  tr {
    border-top-width: 1px;
    border-top-style: solid;
    border-top-color: #dadcde;
    line-height: 23px;
  }

  td {
    padding: 5px 10px;
    font-size: 14px;
    font-family: Verdana;
    width: 100px;
    word-break: break-all; // 元素换行
  }

  // 斑马纹效果stripe
  //tr:nth-child(even) {
  //  background: #F5F7F9;
  //}
  //
  //tr:nth-child(odd) {
  //  background: #FFF;
  //}
}

.el-table .red-row {
  color: red;
}
</style>
<style media="print" lang="scss">
@page {
  size: auto;
  margin: 3mm;
}

@media print {
  html {
    background-color: #ffffff;
    height: auto;
    margin: 0px;
  }

  body {
    border: solid 1px #ffffff;
    margin: 10mm 15mm 10mm 15mm;
  }
  table {
    table-layout: auto !important;
  }

  .el-table__header-wrapper .el-table__header {
    width: 100% !important;
    border: solid 1px #f2f2f2;
  }
  .el-table__body-wrapper .el-table__body {
    width: 100% !important;
  }
  #pagetable table {
    table-layout: fixed !important;
  }
}
</style>
